<template>
    <div class="page-container" v-loading="loading">
        <ComTitle :list="titleList" />
        <el-tabs
            v-if="roles.length"
            v-model="activeRole"
            tab-position="left"
            :before-leave="handleRoleChange"
        >
            <el-tab-pane v-for="role in roles" :label="role.name" :name="role.id" :key="role.id">
                <div>
                    <h3>可操作功能</h3>
                    <SCCheckbox-group
                        v-model="selectMenus"
                        class="checkbox-group"
                        @change="handleChange"
                    >
                        <template v-for="item in menus" :key="item.id">
                            <SCCheckbox
                                v-if="!item.subItems?.length"
                                :label="item.id"
                                :value="item.id"
                                >{{ item.name }}
                            </SCCheckbox>
                            <div v-else class="checkbox-with-chidren">
                                <SCCheckbox
                                    v-model="item.checked"
                                    :indeterminate="item.isIndeterminate"
                                    @change="(val) => handleCheckAllChange(item, val)"
                                    :value="item.id"
                                    :label="item.id"
                                    >{{ item.name }}
                                </SCCheckbox>
                                <SCCheckbox
                                    v-for="subItem in item.subItems"
                                    :label="subItem.id"
                                    :value="subItem.id"
                                    @change="(val) => handleChildChange(item, val)"
                                    :key="subItem.id"
                                >
                                    {{ subItem.name }}
                                </SCCheckbox>
                            </div>
                        </template>
                    </SCCheckbox-group>
                </div>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>
<script setup lang="ts">
import { ref, reactive } from "vue";
import { getRoles, Role, getRolePremissons, updateRolePremissons } from "@/api/roleManage";
import { SCMessage } from "@sribd/sc-ui/lib";
import { useRoute } from "vue-router";
import ComTitle from "@/components/ComTitle.vue";
import { PERMISSION_KEY } from "@/constants/common";
const route = useRoute();
const roles = ref<Role[]>([]);
const loading = ref(true);
const menus = reactive([
    {
        id: PERMISSION_KEY[0].key,
        name: PERMISSION_KEY[0].name,
    },
    {
        id: PERMISSION_KEY[1].key,
        name: PERMISSION_KEY[1].name,
    },
    {
        id: PERMISSION_KEY[2].key,
        name: PERMISSION_KEY[2].name,
    },
    {
        id: PERMISSION_KEY[3].key,
        name: PERMISSION_KEY[3].name,
    },
    {
        id: PERMISSION_KEY[4].key,
        name: PERMISSION_KEY[4].name,
    },
    {
        id: PERMISSION_KEY[5].key,
        name: PERMISSION_KEY[5].name,
    },
    {
        id: PERMISSION_KEY[6].key,
        name: PERMISSION_KEY[6].name,
    },
    {
        id: PERMISSION_KEY[7].key,
        name: PERMISSION_KEY[7].name,
        checked: false,
        isIndeterminate: false,
        subItems: [
            {
                id: PERMISSION_KEY[8].key,
                name: PERMISSION_KEY[8].name,
            },
            {
                id: PERMISSION_KEY[9].key,
                name: PERMISSION_KEY[9].name,
            },
        ],
    },
]);

const titleList = [
    {
        name: "角色管理",
        routeName: "roleManage",
    },
    {
        name: "权限管理",
    },
];

const selectMenus = ref<number[]>([]);
let activeRole = ref<number>();

// 获取角色列表
const params = {
    name: "",
    page: 1,
    pageSize: -1,
};
// getRoles(params)
//     .then((res) => (roles.value = res.list))
//     .catch((error) => SCMessage({ message: error.msg || "获取数据失败", type: "error" }))
//     .finally(() => (loading.value = false));
roles.value = [
    {
        id: 1,
        name: "系统管理员",
    },
    {
        id: 2,
        name: "普通管理员",
    },
];

// 获取角色权限
const getPremissons = (id: number) => {
    return new Promise(async (resolve, reject) => {
        try {
            loading.value = true;
            // const res = await getRolePremissons(id);
            const res = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
            activeRole.value = id;
            selectMenus.value = res;
            formatMenus(res);

            resolve(true);
        } catch (error) {
            SCMessage({ message: error.msg || "获取角色权限失败", type: "error" });
            reject(new Error("获取角色权限失败"));
        } finally {
            loading.value = false;
        }
    });
};

getPremissons(parseInt(route.params.id as string));

const formatMenus = (res) => {
    const nodeWithChild = menus.filter((item) => item.subItems?.length);
    const resSet = new Set(res);
    nodeWithChild.forEach((item) => {
        const childrenSet = new Set(item.subItems?.map((subitem) => subitem.id));
        if (res.indexOf(item.id) > -1) {
            item.checked = true;
            item.isIndeterminate = false;
        } else if (resSet.intersection(childrenSet).size) {
            item.checked = false;
            item.isIndeterminate = true;
        } else {
            item.checked = false;
            item.isIndeterminate = false;
        }
    });
};

const handleRoleChange = async (val) => {
    if (activeRole.value === val) {
        return true;
    }
    return await getPremissons(val);
};

const handleChange = async (val) => {
    // 通过事件触发的变化才能得到最终的菜单
    if (val instanceof Event) {
        console.log(val);
        console.log(selectMenus.value);
        loading.value = true;
        try {
            await updateRolePremissons({
                id: activeRole.value as number,
                permissionList: selectMenus.value,
            });
        } catch (error) {
            SCMessage({ message: error.msg || "修改角色权限失败", type: "error" });
        } finally {
            loading.value = false;
        }
    }
};

const handleCheckAllChange = (item, val) => {
    if (item.subItems.length && !(val instanceof Event)) {
        if (val) {
            selectMenus.value.push(...item.subItems.map((item) => item.id));
            item.checked = true;
            item.isIndeterminate = false;
        } else {
            const subItems = new Set(item.subItems.map((item) => item.id));
            const selected = new Set(selectMenus.value);
            selectMenus.value = Array.from(selected.difference(subItems));
            item.checked = false;
            item.isIndeterminate = false;
        }
    }
};

const handleChildChange = (item, val) => {
    if (item.subItems.length && !(val instanceof Event)) {
        const subItems = new Set(item.subItems.map((item) => item.id));
        const selected = new Set(selectMenus.value);
        const intersection = selected?.intersection(subItems);
        item.checked = intersection.size === subItems.size;
        item.isIndeterminate = intersection.size > 0 && intersection.size < subItems.size;
        // if (item.checked) {
        //     selectMenus.value.push(item.id);
        // } else {
        //     const index = selectMenus.value.indexOf(item.id);
        //     if (index !== -1) {
        //         selectMenus.value.splice(index, 1);
        //     }
        // }
        if (intersection.size == 0) {
            const index = selectMenus.value.indexOf(item.id);
            if (index !== -1) {
                selectMenus.value.splice(index, 1);
            }
        } else {
            const index = selectMenus.value.indexOf(item.id);
            if (index === -1) {
                selectMenus.value.push(item.id);
            }
        }
    }
};
</script>

<style lang="scss" scoped>
:deep(.common-title-box) {
    margin-bottom: 30px;
}
h3 {
    font-size: 16px;
    margin-top: 0;
    margin-bottom: 20px;
}
.checkbox-group {
    display: block;
}
:deep(.el-checkbox-group) {
    display: flex;
    flex-direction: column;
    gap: 10px;
    .sc-checkbox {
        display: block;
        flex: 1;
        padding: 0 17px;
        background: #f8f8fa;
        border-radius: 4px;
        // height: 56px;
        .el-checkbox {
            height: 56px;
        }
    }
    .checkbox-with-chidren {
        display: flex;
        justify-content: flex-start;
        background: #f8f8fa;
        padding: 0 17px;
        gap: 80px;
        .sc-checkbox {
            flex: 0;
            padding: 0;
        }
    }
}
:deep(.el-tabs--left .el-tabs__header.is-left) {
    margin-right: 40px;
}
:deep(.el-tabs__item) {
    padding-right: 94px;
}
:deep(.el-tabs--left .el-tabs__nav-wrap.is-left::after) {
    width: 1px;
}
:deep(.el-tabs--left .el-tabs__nav-scroll) {
    min-height: calc(100vh - 100px);
    padding-top: 20px;
}
</style>
